<?php

  //
  // Memorii Web
  // script/db_word.php
  //
  // Access to the database
  //
  
  // Name of the table
  define('MII_TABLE_WORDS', 'mii_words');
  
	function db_get_word($db_connection, $word_id) {
		db_clear_input($word_id);
		
		$query = 'SELECT * FROM `'.MII_TABLE_WORDS.'` WHERE (`word_id` = \''.$word_id.'\')';
		$result = db_query_array($db_connection, $query);
		if($result)
			return $result;
			
		return array();
	}
	
	function db_get_words($db_connection, $folder_id) {
		db_clear_input($folder_id);
		
		$query = 'SELECT * FROM `'.MII_TABLE_WORDS.'` WHERE (`parent_folder_id` = \''.$folder_id.'\')';
		$result = db_query_arrays($db_connection, $query);
		if($result)
			return $result;
			
		return array();
	}
	
	function db_add_word($db_connection, $parent_folder_id) {
		db_clear_input($root_folder_id);
		
		$new_word_id = db_generate_id();
		
		$query = 'INSERT INTO `'.MII_TABLE_WORDS.'` (`word_id`, `parent_folder_id`, `word`, `reading`, `meaning`, `order`, `fav`, `last_edit`) VALUES (\''.$new_word_id.'\', \''.$parent_folder_id.'\', \'\', \'\', \'\', \'-1\', \'0\', \'NOW()\') ';
		db_query($db_connection, $query);
		
		$query = 'SELECT MAX(`order`) FROM `'.MII_TABLE_WORDS.'` WHERE (`parent_folder_id` = \''.$parent_folder_id.'\')';
		$result = db_query_array($db_connection, $query);
		$query = 'UPDATE `'.MII_TABLE_WORDS.'` SET `order`=\''.(intval($result[0])+1).'\' WHERE (`word_id` = \''.$new_word_id.'\')';
		db_query($db_connection, $query);
	}
	
	function db_edit_word($db_connection, $word_id, $new_word) {
		db_clear_input($word_id);
		db_clear_input($new_word);
		
		$query = 'UPDATE `'.MII_TABLE_WORDS.'` SET `word`=\''.$new_word.'\' WHERE `word_id`=\''.$word_id.'\'';
		db_query($db_connection, $query);
	}
	
	function db_edit_word_reading($db_connection, $word_id, $new_reading) {
		db_clear_input($word_id);
		db_clear_input($new_reading);
		
		$query = 'UPDATE `'.MII_TABLE_WORDS.'` SET `reading`=\''.$new_reading.'\' WHERE `word_id`=\''.$word_id.'\'';
		db_query($db_connection, $query);
	}
	
	function db_edit_word_meaning($db_connection, $word_id, $new_meaning) {
		db_clear_input($word_id);
		db_clear_input($new_meaning);
		
		$query = 'UPDATE `'.MII_TABLE_WORDS.'` SET `meaning`=\''.$new_meaning.'\' WHERE `word_id`=\''.$word_id.'\'';
		db_query($db_connection, $query);
	}
	
	function db_delete_word($db_connection, $word_id) {
		db_clear_input($word_id);
		
		$query = 'DELETE FROM `'.MII_TABLE_WORDS.'` WHERE `word_id`=\''.$word_id.'\' LIMIT 1';
		db_query($db_connection, $query);
	}
?>